//
//  HTBannerAd.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/19.
//

import Foundation
import AppLovinSDK
import SwiftUI

struct HTBannerAd: UIViewRepresentable {
  var var_didLoad: (() -> Void)?

  func makeUIView(context: Context) -> MAAdView {
    let var_adView = MAAdView(adUnitIdentifier: HTConfig.STATIC_bannerId, adFormat: .banner)
    var_adView.delegate = context.coordinator
    if (var_didLoad != nil) {
      context.coordinator.var_didLoad = var_didLoad
    }

    var_adView.setExtraParameterForKey("adaptive_banner", value: "true")

    // Set background or background color for banners to be fully functional
    var_adView.backgroundColor = UIColor.clear

    // Load the first Ad
    var_adView.loadAd()

    return var_adView
  }

  func updateUIView(_ uiView: MAAdView, context: Context) {}

  func makeCoordinator() -> Coordinator {
    Coordinator()
  }
}

extension HTBannerAd {
  class Coordinator: NSObject, MAAdViewAdDelegate {
    var var_didLoad: (() -> Void)?

    // MARK: MAAdDelegate Protocol
    func didLoad(_ ad: MAAd) {
      if (var_didLoad != nil) {
        var_didLoad!()
      }
    }

    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
    }

    func didClick(_ ad: MAAd) {}

    func didFail(toDisplay ad: MAAd, withError error: MAError) {
    }

    // MARK: MAAdViewAdDelegate Protocol

    func didExpand(_ ad: MAAd) {}

    func didCollapse(_ ad: MAAd) {}

    // MARK: Deprecated Callbacks

    func didDisplay(_ ad: MAAd) { /* use this for impression tracking */ }
    func didHide(_ ad: MAAd) { /* DO NOT USE - THIS IS RESERVED FOR FULLSCREEN ADS ONLY AND WILL BE REMOVED IN A FUTURE SDK RELEASE */ }
  }
}
